package com.quran.viewcontrollers;

import java.io.File;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bappi.utils.AlertUtils;
import com.bappi.utils.Constants;
import com.bappi.utils.FileUtils;
import com.bappi.utils.MediaPlayerUtils;
import com.bappi.utils.Utils;
import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.tos.quran.R;

public class Tab3Controller extends AbstractViewController {

	private RelativeLayout searchLayout;
	private Action showSearchAction;
	private Action hideSearchAction;
	private Button searchButton;
	private AutoCompleteTextView searchAutoCompleteTextView;

	private List<String[]> versesInfos;
	private VersesListAdapter versesListAdapter;
	private ListView listView;

	private String langCode;

	// private HashMap<String, String> hashRender;
	private ActionBar actionBar;
	// private Typeface arabicTypeface, bengaliTypeface, hindiTypeface;
	private int currentPlayingIndex;

	private boolean isPaused;
	private View buttonContainer, bottomHelperLayout;
	private ImageButton playPauseButton, prevButton, nextButton;
	private boolean isNoTranslateSelected;

	private OnCompletionListener onCompletionListener = new OnCompletionListener() {

		public void onCompletion(MediaPlayer mp) {
			try {
				currentPlayingIndex = -1;
				hideButtonPanel();
				versesListAdapter.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	};

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		try {
			if (Constants.KEY_SELECTED_TRANS_CODE.equals(key)) {
				langCode = getSharedPreferences().getString(
						Constants.KEY_SELECTED_TRANS_CODE,
						Constants.LANG_CODE_NONE);
				isNoTranslateSelected = Constants.LANG_CODE_NONE
						.equals(langCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	};

	private final TextWatcher textWatcher = new TextWatcher() {

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			try {
				String text = searchAutoCompleteTextView.getText().toString();
				List<String> words = new ArrayList<String>();
				if (text.length() > 1) {
					if (Utils.containsArabicLetters(text)) {
						words = getActivity().getDatabaseAccessor()
								.searchWords("verses_words", text, 5);
					} else {
						words = getActivity().getDatabaseAccessor()
								.searchWords(langCode + "_words", text, 5);
					}
				}
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						getActivity(), android.R.layout.simple_list_item_1,
						android.R.id.text1, words);
				searchAutoCompleteTextView.setAdapter(adapter);
			} catch (Exception e) {

			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		public void afterTextChanged(Editable s) {
		}
	};

	public Tab3Controller(AbstractTabRootManager tabRootManager) {
		super(tabRootManager, R.layout.tab3_view);
		try {

			langCode = getSharedPreferences().getString(
					Constants.KEY_SELECTED_TRANS_CODE,
					Constants.LANG_CODE_DEFAULT);
			isNoTranslateSelected = Constants.LANG_CODE_NONE.equals(langCode);
			currentPlayingIndex = -1;
			searchButton = (Button) findViewById(R.id.search_button);
			searchAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.search_field);
			searchLayout = (RelativeLayout) findViewById(R.id.search_layout);
			actionBar = (ActionBar) findViewById(R.id.actionbar);
			showSearchAction = new Action() {
				public void performAction(View view) {
					actionBar.removeAction(this);
					actionBar.addAction(hideSearchAction);
					searchLayout.setVisibility(View.VISIBLE);
				}

				public int getDrawable() {
					return R.drawable.ic_menu_search;
				}
			};
			hideSearchAction = new Action() {
				public void performAction(View view) {
					actionBar.removeAction(this);
					actionBar.addAction(showSearchAction);
					searchLayout.setVisibility(View.GONE);
				}

				public int getDrawable() {
					return R.drawable.ic_menu_search_hide;
				}
			};
			actionBar.setTitle(getString(R.string.text_tab3));
			searchAutoCompleteTextView.addTextChangedListener(textWatcher);
			searchAutoCompleteTextView
					.setOnItemClickListener(new AdapterView.OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int position, long arg3) {
							try {
								Utils.hideKeyboard(getActivity());
								searchAndShow(searchAutoCompleteTextView
										.getText().toString());
								// if (customKeyboard != null) {
								// customKeyboard.hideCustomKeyboard();
								// }
								// String inputText =
								// inputField.getText().toString();
								// if ((!isEnglishMode)) {
								// String text = wordMapping.get(inputText);
								// wordMapping.clear();
								// if ((text != null) &&
								// (!inputText.equals(text))) {
								// inputText = text;
								// hideAutoCompletePopUp = true;
								// inputField.setText(inputText);
								// inputField.setSelection(inputField.length());
								// }
								// }
								// process(inputText, false, false);
							} catch (Exception e) {
							}
						}
					});
			searchAutoCompleteTextView
					.setOnEditorActionListener(new TextView.OnEditorActionListener() {
						@Override
						public boolean onEditorAction(TextView v, int actionId,
								KeyEvent event) {
							if (actionId == EditorInfo.IME_ACTION_SEARCH
									|| ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event
											.getAction() == KeyEvent.ACTION_DOWN))) {
								try {
									searchAutoCompleteTextView
											.dismissDropDown();
									Utils.hideKeyboard(getActivity());
									searchAndShow(searchAutoCompleteTextView
											.getText().toString());

								} catch (Exception e) {
								}
								return true;
							}
							return false;
						}
					});
			searchButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					String searchkey = searchAutoCompleteTextView.getText()
							.toString();
					if (searchkey != null && searchkey.length() > 0) {
						searchAndShow(searchkey);
					} else {
						Utils.showAlertDialog(getActivity(),
								getString(R.string.enter_search_key));
					}
				}
			});
			// actionBar.addAction(showSearchAction);
			actionBar.addAction(hideSearchAction);

			listView = (ListView) findViewById(R.id.list_view);
			buttonContainer = findViewById(R.id.bottom_layout);
			bottomHelperLayout = findViewById(R.id.bottom_helper_layout);
			playPauseButton = (ImageButton) findViewById(R.id.play_pause_button);
			prevButton = (ImageButton) findViewById(R.id.prev_button);
			nextButton = (ImageButton) findViewById(R.id.next_button);
			playPauseButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (isPaused) {
							MediaPlayerUtils.play();
							isPaused = false;
						} else {
							MediaPlayerUtils.pause();
							isPaused = true;
						}
						manageButtons();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			nextButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (currentPlayingIndex < (versesInfos.size() - 1)) {
							currentPlayingIndex++;
							play();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			prevButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (currentPlayingIndex > 0) {
							currentPlayingIndex--;
							play();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			versesListAdapter = new VersesListAdapter();
			listView.setAdapter(versesListAdapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				public void onItemClick(AdapterView<?> av, View v,
						int position, long arg) {
					versesClicked(position);
				}
			});
			listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

				public boolean onItemLongClick(AdapterView<?> av, View v,
						int position, long arg) {
					versesLongClicked(position);
					return true;
				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onDestroy() {
		try {
			MediaPlayerUtils.stopPlaying();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void searchAndShow(final String searchKey) {
		try {
			new AsyncTask<String, String, String>() {
				private AlertUtils.SpinnerProgressDialog spinnerProgressDialog;

				@Override
				protected void onPreExecute() {
					try {
						spinnerProgressDialog = AlertUtils.getProgressDialog(
								getActivity(),
								getString(R.string.dialog_default_title),
								getString(R.string.please_wait));
						spinnerProgressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {

						// boolean containsArabicChar = Utils
						// .containsArabicLetters(searchKey);
						// langCode = getSharedPreferences().getString(
						// Constants.KEY_SELECTED_TRANS_CODE,
						// Constants.LANG_CODE_NONE);
						isNoTranslateSelected = Constants.LANG_CODE_NONE
								.equals(langCode);
						// if (containsArabicChar) {
						versesInfos = getActivity().getDatabaseAccessor()
								.searchVerses(langCode, searchKey, 50);
						// }else{
						//
						// }

					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						versesListAdapter.notifyDataSetChanged();
						spinnerProgressDialog.dismiss();
						if (versesInfos.size() == 0) {
							Utils.showAlertDialog(getActivity(),
									getString(R.string.no_matching_found));
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class VersesListAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public VersesListAdapter() {
			mInflater = (LayoutInflater) getActivity().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return versesInfos == null ? 0 : versesInfos.size();
		}

		public Object getItem(int arg0) {
			Object ret = null;
			if (versesInfos != null && versesInfos.size() > arg0) {
				ret = versesInfos.get(arg0);
			}
			return ret;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			try {
				ViewHolder holder;
				if (convertView == null) {
					convertView = mInflater.inflate(
							R.layout.search_list_content, null);
					holder = new ViewHolder();
					holder.mainContainer = convertView
							.findViewById(R.id.main_container);

					holder.suraNameEn = (TextView) convertView
							.findViewById(R.id.view_sura_name_eng);
					holder.suraNameAr = (TextView) convertView
							.findViewById(R.id.view_sura_name_ara);
					holder.verseNo = (TextView) convertView
							.findViewById(R.id.view_verse_no);

					holder.versesAra = (TextView) convertView
							.findViewById(R.id.view_verses_ara);
					// holder.versesAra.setLineSpacing(Constants.SPACING_FACTOR
					// * holder.versesAra.getPaint().getTextSize(), 1);
					// holder.versesAra.setTypeface(arabicTypeface);
					holder.versesOthers = (TextView) convertView
							.findViewById(R.id.view_verses_others);
					if (isNoTranslateSelected) {
						holder.versesOthers.setVisibility(View.GONE);
					} else {
						holder.versesOthers.setVisibility(View.VISIBLE);
						// if (Constants.LANG_CODE_BENGALI.equals(langCode)) {
						// holder.versesOthers.setLineSpacing(6, 1);
						// holder.versesOthers.setTypeface(bengaliTypeface);
						// } else if
						// (Constants.LANG_CODE_PERSIAN.equals(langCode)) {
						// holder.versesOthers.setTypeface(arabicTypeface);
						// holder.versesOthers.setTextSize(
						// TypedValue.COMPLEX_UNIT_PX,
						// holder.versesAra.getTextSize());
						// holder.versesOthers.setGravity(Gravity.RIGHT);
						// } else if
						// (Constants.LANG_CODE_HINDI.equals(langCode)) {
						// holder.versesOthers.setTypeface(hindiTypeface);
						// }
					}
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				// holder.versesAra.setSpecialChars(versesInfos.get(position)[2]);
				holder.versesAra.setText(versesInfos.get(position)[1]);
				if (!isNoTranslateSelected) {
					holder.versesOthers.setText(versesInfos.get(position)[3]);
				}
				holder.suraNameEn.setText(versesInfos.get(position)[6]);
				holder.suraNameAr.setText(versesInfos.get(position)[5]);
				holder.verseNo
						.setText("(" + versesInfos.get(position)[8] + ")");
				if (currentPlayingIndex == position) {
					holder.mainContainer.setBackgroundColor(0x44000000);
				} else {
					holder.mainContainer.setBackgroundColor(0x00000000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			View mainContainer;
			TextView suraNameEn;
			TextView suraNameAr;
			TextView verseNo;
			TextView versesAra;
			TextView versesOthers;
		}
	}

	private void versesLongClicked(final int position) {
		try {
			final Dialog dialog = new Dialog(getActivity());
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.verses_options);
			dialog.setCancelable(false);
			Button buttonAddToBookmark = (Button) dialog
					.findViewById(R.id.button_add_to_bookmark);
			Button buttonShare = (Button) dialog
					.findViewById(R.id.button_share);
			Button buttonCancel = (Button) dialog
					.findViewById(R.id.button_cancel);
			if (!Utils.isShareable(langCode)) {
				buttonShare.setVisibility(View.GONE);
			}
			buttonAddToBookmark.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dialog.dismiss();
					addToBookmark(position);
				}
			});
			buttonShare.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					dialog.dismiss();
					Intent sharingIntent = new Intent(Intent.ACTION_SEND);
					// sharingIntent.setType("text/html");
					sharingIntent.setType("text/plain");
					sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
							versesInfos.get(position)[3]);
					getActivity().startActivity(
							Intent.createChooser(sharingIntent,
									getString(R.string.sharing_intent_title)));
				}
			});
			buttonCancel.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void play() throws Exception {
		isPaused = false;
		manageButtons();
		showButtonPanel();
		versesListAdapter.notifyDataSetChanged();
		if ((currentPlayingIndex < listView.getFirstVisiblePosition())
				|| (currentPlayingIndex >= listView.getLastVisiblePosition())) {
			listView.setSelection(currentPlayingIndex);
		}

		MediaPlayerUtils.playFile(getActivity(), FileUtils.getFile(
				getActivity(), versesInfos.get(currentPlayingIndex)[4], String
						.format("%03d%03d.mp3", Integer.parseInt(versesInfos
								.get(currentPlayingIndex)[4]),
								Integer.parseInt(versesInfos
										.get(currentPlayingIndex)[8]))),
				onCompletionListener);
	}

	private void addToBookmark(final int position) {
		try {
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;
				private boolean added;

				@Override
				protected void onPreExecute() {
					try {
						progressDialog = new ProgressDialog(getActivity());
						progressDialog
								.setProgressStyle(ProgressDialog.STYLE_SPINNER);
						progressDialog.setCancelable(true);
						progressDialog.setIndeterminate(true);
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					String[] info = versesInfos.get(position);
					int versesId = Integer.parseInt(info[0]);

					added = getActivity().getDatabaseAccessor().addToBookmark(
							versesId, Integer.parseInt(info[4]),
							Integer.parseInt(versesInfos.get(position)[8]),
							info[5], info[6], info[7]);
					getSharedPreferences()
							.edit()
							.putLong(Constants.KEY_BOOKMARK_CHANGED_CODE,
									System.currentTimeMillis()).commit();
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						progressDialog.dismiss();
						if (added) {
							Utils.showAlertDialog(getActivity(),
									getString(R.string.added_to_bookmark));
						} else {
							Utils.showAlertDialog(
									getActivity(),
									getString(R.string.already_added_to_bookmark));
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void versesClicked(final int position) {
		try {
			File file = FileUtils.getFile(getActivity(), versesInfos
					.get(position)[4], String.format("%03d%03d.mp3",
					Integer.parseInt(versesInfos.get(position)[4]),
					Integer.parseInt(versesInfos.get(position)[8])));
			if (file.exists() && file.isFile()) {
				currentPlayingIndex = position;
				play();
			} else {
				Utils.showAlertDialogYesNo(getActivity(),
						getString(R.string.message_download_conf),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								downloadFile(position);
							}
						}, new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {

							}
						});

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void downloadFile(final int position) {
		try {
			try {
				new AsyncTask<String, String, String>() {
					private String exception;
					private ProgressDialog progressDialog;

					protected void onPreExecute() {
						try {
							progressDialog = Utils
									.getProgressDialog(getActivity());
							progressDialog.show();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					protected String doInBackground(String... arg0) {
						try {
							FileUtils
									.downloadVerse(getActivity(),
											Constants.FILE_DOWNLOAD_URL,
											Integer.parseInt(versesInfos
													.get(position)[4]), Integer
													.parseInt(versesInfos
															.get(position)[8]));
						} catch (UnknownHostException uhe) {
							exception = getString(R.string.message_go_online);
							uhe.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
							exception = e.getLocalizedMessage();
						}
						return null;
					}

					protected void onPostExecute(String unused) {
						try {
							progressDialog.dismiss();
							if (exception != null) {
								Utils.showAlertDialog(getActivity(), exception);
							} else {
								currentPlayingIndex = position;
								play();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.execute();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void manageButtons() {
		try {
			if (currentPlayingIndex > 0) {
				prevButton.setEnabled(true);
			} else {
				prevButton.setEnabled(false);
			}
			if (currentPlayingIndex < (versesInfos.size() - 1)) {
				nextButton.setEnabled(true);
			} else {
				nextButton.setEnabled(false);
			}
			if (isPaused) {
				playPauseButton.setImageResource(R.drawable.play);
			} else {
				playPauseButton.setImageResource(R.drawable.pause);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showButtonPanel() {
		try {
			if (buttonContainer.getVisibility() != View.VISIBLE) {

				Animation animation = new TranslateAnimation(
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 1.0f,
						Animation.RELATIVE_TO_SELF, 0.0f);
				animation.setDuration(600);
				animation
						.setAnimationListener(new Animation.AnimationListener() {

							public void onAnimationStart(Animation animation) {
								// TODO Auto-generated method stub

							}

							public void onAnimationRepeat(Animation animation) {
								// TODO Auto-generated method stub

							}

							public void onAnimationEnd(Animation animation) {
								try {
									bottomHelperLayout.getLayoutParams().height = buttonContainer
											.getHeight();
									listView.requestLayout();
								} catch (Exception e) {
									e.printStackTrace();
								}

							}
						});
				buttonContainer.startAnimation(animation);
				buttonContainer.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void hideButtonPanel() {
		try {
			if (buttonContainer.getVisibility() == View.VISIBLE) {
				bottomHelperLayout.getLayoutParams().height = 0;
				Animation animation = new TranslateAnimation(
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 1.0f);
				animation.setDuration(600);
				buttonContainer.startAnimation(animation);
				buttonContainer.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
